<?php namespace Phpcmf\Model;

// tag模型类

class Tag extends \Phpcmf\Model
{

    protected $tablename;
    protected $link_cache;


    public function __construct(...$params)
    {
        parent::__construct(...$params);
        $this->tablename = SITE_ID.'_tag';
        $this->link_cache = WRITEPATH.'tags/';
    }
    
    // 通过关键字获取tag
    public function tag_row($id) {
        
        // 首先查询
        $data = $this->db->table($this->tablename)->where('id', (int)$id)->get()->getRowArray();

        $data && $this->db->table($this->tablename)->where('id', (int)$id)->set('hits', intval($data['hits'])+1)->update();

        return $data;
    }

    // 检查别名是否可用
    public function check_code($id, $value) {

        if (!$value) {
            return 1;
        }

        return $this->table($this->tablename)->is_exists($id, 'code', $value);
    }

    // 检查名称是否可用
    public function check_name($id, $value) {

        if (!$value) {
            return 1;
        }

        return $this->table($this->tablename)->is_exists($id, 'name', $value);
    }

    // 批量
    public function save_all_data($pid, $data) {

        $c = 0;
        $py = \Phpcmf\Service::L('pinyin'); // 拼音转换类
        $names = explode(PHP_EOL, trim($data));
        foreach ($names as $t) {
            $t = trim($t);
            if (!$t) {
                continue;
            } elseif ($this->check_name(0, $t)) {
                return dr_return_data(0, dr_lang('tag【%s】已经存在', $t));
            }
            $cname = $py->result($t);
            $count = $this->db->table($this->tablename)->where('code', $cname)->countAllResults();
            $code = $count ? $cname.$count : $cname;
            $pcode = $this->get_pcode(['pid' => $pid, 'code' => $code]);
            $url = \Phpcmf\Service::L('router')->tag_url($pcode);
            $rt = $this->table($this->tablename)->insert(array(
                'pid' => $pid,
                'name' => $t,
                'code' => $code,
                'pcode' => $pcode,
                'hits' => 0,
                'total' => 0,
                'displayorder' => 0,
                'childids' => '',
                'content' => '',
                'url' => $url,
            ));
            if (!$rt['code']) {
                return $rt;
            }
            $c++;
        }
        return dr_return_data(1, dr_lang('批量添加%s个', $c));
    }

    // save
    public function save_data($id, $data) {
        $this->table($this->tablename)->update($id, $data);
    }

   
    // 获取pcode
    public function get_pcode($data) {
        
        if (!$data['pid']) {
            return $data['code'];
        }
        
        $row = $this->table($this->tablename)->get($data['pid']);
        
        return trim($row['code'].'/'.$data['code'], '/');
        
    }

    // 缓存链接，用于内链
    private function _save_tag_cache($siteid, $name, $url) {
        $file = md5($siteid.'-'.$name);
        file_put_contents($this->link_cache.$file, $url);
    }

    // 缓存
    public function cache($siteid = SITE_ID) {

        dr_dir_delete($this->link_cache);
        if (!is_dir($this->link_cache)) {
            dr_mkdirs($this->link_cache);
        }

        $cache = [];
        $result = $this->table($siteid.'_tag')->where('pid', 0)->order_by('displayorder DESC,id ASC')->getAll();
        if ($result) {
            foreach ($result as $data) {
                $tag = $data['name'];
                $ids = $code = [];
                $result2 = $this->table($siteid.'_tag')->where('pid', $data['id'])->order_by('displayorder DESC,id ASC')->getAll();
                if ($result2) {
                    foreach ($result2 as $data2) {
                        $tag.= ','.$data2['name'];
                        $ids[] = $data2['id'];
                        $code[] = $data2['code'];
                        $url = \Phpcmf\Service::L('router')->tag_url($data2['pcode']);
                        $cache[$data2['code']] = [
                            'id' => $data2['id'],
                            'pid' => $data['code'],
                            'name' => $data2['name'],
                            'codes' => '',
                            'tags' => $data2['name'],
                            'total' => 0,
                            'childids' => [$data2['id']],
                            'url' => $url,
                        ];
                        $this->table($siteid.'_tag')->update($data2['id'], [
                            'url' => $url,
                            'total' => 0
                        ]);
                        $this->_save_tag_cache($siteid, $data2['name'], $url);
                    }
                }
                $url = \Phpcmf\Service::L('router')->tag_url($data['pcode']);
                $this->_save_tag_cache($siteid, $data['name'], $url);
                $cache[$data['code']] = [
                    'id' => $data['id'],
                    'pid' => '',
                    'name' => $data['name'],
                    'tags' => trim($tag, ','),
                    'codes' => $code,
                    'total' => count($result2),
                    'childids' => $ids,
                    'url' => $url,
                ];
                $this->table($siteid.'_tag')->update($data['id'], [
                    'url' => $url,
                    'total' => $cache[$data['code']]['total']
                ]);
            }
        }
        // 写入缓存
        \Phpcmf\Service::L('cache')->set_file('tag-'.$siteid, $cache);

        // 自定义字段
        $cache2 = [];
        $field = $this->db->table('field')->where('disabled', 0)->where('relatedid', $siteid)->where('relatedname', 'tag')->orderBy('displayorder ASC,id ASC')->get()->getResultArray();
        if ($field) {
            foreach ($field as $f) {
                $f['setting'] = dr_string2array($f['setting']);
                $cache2[$f['fieldname']] = $f;
            }
        }
        \Phpcmf\Service::L('cache')->set_file('tag-'.$siteid.'-field', $cache2);

        return $cache;
    }
}